//
//  ViewController.m
//  MapList
//
//  Created by Wu Chenhao on 6/2/12.
//  Copyright (c) 2012 MicroStrategy. All rights reserved.
//

#import "HomeViewController.h"
#import "UserSettingViewController.h"
#import "ActivityInfo.h"
#import "ActivityView.h"
#import "UIColor+XMin.h"
#import "HelpView.h"
#import "TutorialViewController.h"
@implementation HomeViewController

@synthesize infoView;
@synthesize avatarView;
@synthesize shareButton;
@synthesize helpButton;
@synthesize exitButton;
@synthesize mileStone;
@synthesize userName;
@synthesize divLine;
@synthesize contentView;
@synthesize avatar;
@synthesize staticInfo;
@synthesize actList;
@synthesize requestUtil;
@synthesize activityViewController;

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - Event Handler
- (void) shareButtonClicked
{
    
}

- (void) helpButtonClicked
{
    
}

- (void) exitButtonClicked
{
    UserSettingViewController *settingViewController=[[UserSettingViewController alloc]initWithNibName:@"UserSettingViewController" bundle:nil];
    [self.navigationController pushViewController:settingViewController animated:YES];
}
#pragma mark - View Initialization
- (void)initInfoView
{
    infoView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 127)];
    infoView.backgroundColor = [UIColor getColor:@"E6E6E6"];
    
    //add avatarView
    avatarView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 85, 85)];
    UIImage *avatarFrame = [UIImage imageNamed:@"头像边框.png"];
    avatarView.image = avatarFrame;
    NSString *bava = staticInfo.user.bavatorUrl;
    NSURL *url = [NSURL URLWithString:bava];
    
    UIImage *avatarImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
    avatar = [[UIImageView alloc] initWithFrame:CGRectMake(2, 2, 81, 81)];
    avatar.image = avatarImage;
    [avatarView addSubview:avatar];
    [infoView addSubview:avatarView];
    
    //add userName
    userName = [[UILabel alloc] initWithFrame:CGRectMake(10, 100, 85, 15)];
    userName.text = staticInfo.user.name;
    userName.textAlignment = UITextAlignmentCenter;
    userName.textColor = [UIColor getColor:@"696969"];
    userName.backgroundColor = [UIColor clearColor];
    userName.font = [UIFont fontWithName:@"Arial" size:15];
    [infoView addSubview:userName];
    
    //add share button
//    shareButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    [shareButton setFrame:CGRectMake(179, 10, 25, 25)];
//    [shareButton setBackgroundImage:[UIImage imageNamed:@"shareButton1.png"] forState:UIControlStateNormal];
//    [shareButton setBackgroundImage:[UIImage imageNamed:@"shareButton2.png"] forState:UIControlStateHighlighted];
//    [shareButton addTarget:self action:@selector(shareButtonClicked)forControlEvents:UIControlEventTouchUpInside];
//    [infoView addSubview:shareButton];
//    
//    //add help button
//    helpButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    [helpButton setFrame:CGRectMake(228, 10, 25, 25)];
//    [helpButton setBackgroundImage:[UIImage imageNamed:@"helpButton1.png"] forState:UIControlStateNormal];
//    [helpButton setBackgroundImage:[UIImage imageNamed:@"helpButton2.png"] forState:UIControlStateHighlighted];
//    [helpButton addTarget:self action:@selector(helpButtonClicked) forControlEvents:UIControlEventTouchUpInside];
//    [infoView addSubview:helpButton];
    
    //add exit button
    exitButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [exitButton setFrame:CGRectMake(277, 10, 25, 25)];
    [exitButton setBackgroundImage:[UIImage imageNamed:@"exitButton1.png"] forState:UIControlStateNormal];
    [exitButton setBackgroundImage:[UIImage imageNamed:@"exitButton2.png"] forState:UIControlStateHighlighted];
    [exitButton addTarget:self action:@selector(exitButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    [infoView addSubview:exitButton];
    
    //add mileStone
    mileStone = [[UILabel alloc] initWithFrame:CGRectMake(103, 55, 200, 40)];
    float distance=[staticInfo.user.totalDistance longLongValue]*1.0/1000;
    mileStone.text = [NSString stringWithFormat:@"%0.2lf km",distance];
    mileStone.textAlignment = UITextAlignmentLeft;
    mileStone.textColor = [UIColor getColor:@"5CC1DE"];
    mileStone.backgroundColor = [UIColor clearColor];
    mileStone.font = [UIFont fontWithName:@"Arial" size:30];
    [infoView addSubview:mileStone];
    
    [self.view addSubview:infoView];
}

- (void)initTableView
{
    contentView = [[UIView alloc]initWithFrame:CGRectMake(0, 128, 320, 332)];
    contentView.backgroundColor = [UIColor getColor:@"E6E6E6"];
    [self.view addSubview:contentView];
    if(staticInfo.user.nowRiddingCount>0){
        activityViewController = [[ActivityViewController alloc]init];
        [activityViewController.view setFrame:CGRectMake(10, 10, 320, 470)];
        activityViewController.view.backgroundColor = [UIColor clearColor];
        [contentView addSubview:activityViewController.tableView];
    }else{
        UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(20, 10, 200, 20)];
        label.text=@"您还没有骑行活动噢~";
        label.backgroundColor=[UIColor clearColor];
        [label setFont:[UIFont systemFontOfSize:14]];
        [contentView addSubview:label];
        
        UIButton *refreshBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [refreshBtn setFrame:CGRectMake(260, 10, 40, 20)];
        [refreshBtn addTarget:self action:@selector(refreshView) forControlEvents:UIControlEventTouchUpInside];
        refreshBtn.titleLabel.text=@"刷新?";
        refreshBtn.titleLabel.font=[UIFont systemFontOfSize:14];
        refreshBtn.titleLabel.textColor=[UIColor getColor:@"5cc1de"];
        [contentView addSubview:refreshBtn];
        
        UIView *helpCreateView=[[UIView alloc]initWithFrame:CGRectMake(20, 50, 280, 80)];
        UITapGestureRecognizer *viewTap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(createViewTap:)]; //动态添加点击操作
        [helpCreateView addGestureRecognizer:viewTap];
        helpCreateView.backgroundColor=[UIColor getColor:@"f15e1d"];
        UILabel *helpCreateLabel=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 280, 80)];
        helpCreateLabel.text=@"如何创建骑行活动?";
        [helpCreateLabel setTextAlignment:UITextAlignmentCenter];
        helpCreateLabel.backgroundColor=[UIColor clearColor];
        [helpCreateLabel setFont:[UIFont systemFontOfSize:20]];
        [helpCreateView addSubview:helpCreateLabel];
        [contentView addSubview:helpCreateView];
    }
    
}


-(void)refreshView{
    dispatch_queue_t q;
    q=dispatch_queue_create("refreshView", NULL);
    dispatch_async(q, ^{
        NSDictionary *userProfileDic = [requestUtil getUserProfile];
        NSLog(@"%d",[[userProfileDic objectForKey:@"riddingCount"]intValue]);
        staticInfo.user.nowRiddingCount=[[userProfileDic objectForKey:@"riddingCount"]intValue];
        dispatch_async(dispatch_get_main_queue(), ^{
            if(staticInfo.user.nowRiddingCount>0){
                for(UIView *view in contentView.subviews){
                    [view removeFromSuperview];
                }
                activityViewController = [[ActivityViewController alloc]init];
                [activityViewController.view setFrame:CGRectMake(10, 10, 320, 470)];
                activityViewController.view.backgroundColor = [UIColor clearColor];
                [contentView addSubview:activityViewController.tableView];
            }
        });
    });
                       
}
-(void)createViewTap:(UITapGestureRecognizer*) gestureRecognize{
    TutorialViewController *tutorialViewController = [[TutorialViewController alloc]initWithNibName:@"TutorialViewController" bundle:nil];
    [self.navigationController pushViewController:tutorialViewController animated:YES];
}

- (void)addDivLine
{
    divLine = [[UIImageView alloc]initWithFrame:CGRectMake(0, 127, 320, 1)];
    UIImage *divLineImage = [UIImage imageNamed:@"分割线.png"];
    divLine.image = divLineImage;
    [self.view addSubview:divLine];
    
}



#pragma mark - View lifecycle

- (void)viewDidLoad
{
    staticInfo=[StaticInfo getSinglton];
    actList=[[NSMutableArray alloc]init];
    requestUtil=[RequestUtil getSinglton];
    
    [self initInfoView];
    [self addDivLine];
    [super viewDidLoad];
    [self initTableView];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(finishRidding:) name:kFinishNotification object:nil];
}

- (void)finishRidding:(NSNotification*)noti
{
    NSDictionary *dic=[noti userInfo];
    if ([[noti name] isEqualToString:kFinishNotification]) {
        mileStone.text=[dic objectForKey:@"distance"];
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = YES;
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait||interfaceOrientation ==UIInterfaceOrientationPortraitUpsideDown);
}

#pragma mark - Data Initialization

-(void)initActList:(NSString*)limit createTime:(NSString*)createTime{
//    NSArray *array=[requestUtil getUserMaps:limit createTime:createTime];
//    
//    NSLog(@"getUserMapsResponse: %@", [array description]);
//    if(array&&[array count]>0){
//        actList = [[NSMutableArray alloc] init];
//        for (NSDictionary *dic in array) {
//            ActivityInfo *actInfo = [[ActivityInfo alloc] init];
//            actInfo.name = [dic objectForKey:@"name"];
//            actInfo.id = [dic objectForKey:@"id"];
//            actInfo.distance = [dic objectForKey:@"distance"];
//            NSLog(@"distance: %@", actInfo.distance);
//            actInfo.status = [dic objectForKey:@"status"];
//            actInfo.name = [dic objectForKey:@"name"];
//            actInfo.beginLocation = [dic objectForKey:@"beginLocation"];
//            [actList addObject:actInfo];
//            NSLog(@"%u", [actList count]);
//        }
//        activityViewController.activities = actList;
//        NSLog(@"%u", [activityViewController.activities count]);        
//    }
//    else {
//        [self.navigationController popViewControllerAnimated:YES];
//    }
}

@end
